import { useMount } from 'ahooks';
import { App, Button, Input, Select } from 'antd';
import React, { useCallback, useEffect, useMemo } from 'react';

import FormLabel from '@/components/MyBox/FormLabel';
import MyModal from '@/components/MyModal';
import { t } from '@/locales/i18n';
import { getNanoid } from '@/pages/chat/tools/tools';
import {
  FlowNodeInputTypeEnum,
  FlowValueTypeMap,
  WorkflowIOValueTypeEnum,
} from '@/types/workflow/constant';
import { FlowNodeInputItemType, FlowNodeOutputItemType } from '@/types/workflow/io';

const { TextArea } = Input;

const FieldModal = ({
  customInputConfig,
  defaultInput,
  keys,
  onClose,
  onSubmit,
}: {
  customInputConfig: any;
  defaultInput: FlowNodeInputItemType;
  keys: string[];
  onClose: () => void;
  onSubmit: (e: { data: FlowNodeInputItemType; isChangeKey: boolean }) => void;
}) => {
  const { message } = App.useApp();
  const isEdit = !!defaultInput.key;
  const [data, setData] = React.useState<FlowNodeInputItemType>(defaultInput);
  const inputType = FlowNodeInputTypeEnum.reference;

  const showValueTypeSelect = useMemo(() => {
    if (!customInputConfig.selectValueTypeList || customInputConfig.selectValueTypeList.length <= 1)
      return false;
    if (inputType === FlowNodeInputTypeEnum.reference) return true;

    return false;
  }, [customInputConfig.selectValueTypeList, inputType]);

  const valueTypeSelectList = useMemo(() => {
    if (!customInputConfig.selectValueTypeList) return [];

    const dataTypeSelectList = Object.values(FlowValueTypeMap).map((item) => ({
      label: t(item.label as any),
      value: item.value,
    }));

    return dataTypeSelectList.filter((item) =>
      customInputConfig.selectValueTypeList?.includes(item.value),
    );
  }, [customInputConfig.selectValueTypeList]);

  const onSubmitSuccess = useCallback(
    (data: FlowNodeOutputItemType) => {
      if (!data.key) {
        message.warning('请输入参数名！');
        return;
      }
      const isChangeKey = defaultInput.key !== data.key;

      if (keys.includes(data.key)) {
        // 只要编辑状态，且未改变key，就不提示
        if (!isEdit || isChangeKey) {
          message.warning(t('field_name_already_exists'));
          return;
        }
      }

      data.id = data.id || getNanoid();
      data.key = data?.key?.trim();
      data.label = data.key;

      onSubmit({
        data: data as any,
        isChangeKey,
      });
      onClose();
    },
    [defaultInput.key, isEdit, keys, onClose, onSubmit, message],
  );

  useMount(() => {
    if (
      customInputConfig.selectValueTypeList &&
      customInputConfig.selectValueTypeList.length > 0 &&
      !data.valueType
    ) {
      setData({
        ...data,
        valueType: customInputConfig.selectValueTypeList[0] as WorkflowIOValueTypeEnum,
      });
    }
  });

  useEffect(() => {
    // setValueType(defaultValue.valueType);
    // setKey(defaultValue.key);
    setData(defaultInput);
  }, [defaultInput]);

  return (
    <MyModal
      isOpen
      iconSrc="menu_set"
      title={isEdit ? t('edit_output') : t('add_new_output')}
      // overflow={'unset'}
      className="overflow-hidden"
      minW="400px"
    >
      <div className="flex w-full flex-col overflow-auto">
        <div className="w-full space-x-3">
          {showValueTypeSelect && (
            <div className="flex items-center">
              <FormLabel>{t('core.module.Data Type')}</FormLabel>
              <div className="ml-2 flex-1">
                <Select
                  className="w-full"
                  popupClassName="workflow-dropdown"
                  options={valueTypeSelectList.filter(
                    (item) => item.value !== WorkflowIOValueTypeEnum.arrayAny,
                  )}
                  value={data.valueType}
                  onChange={(e) => {
                    setData({
                      ...data,
                      valueType: e as WorkflowIOValueTypeEnum,
                    });
                  }}
                />
              </div>
            </div>
          )}

          {/* key */}
          <div className="mt-3 flex items-center">
            <FormLabel required>{t('Variable_name')}</FormLabel>
            <div className="ml-2 flex-1">
              {' '}
              <Input
                className="ml-2 bg-gray-100"
                placeholder="appointment/sql"
                value={data.key}
                onChange={(e) => {
                  setData({
                    ...data,
                    key: e.target.value,
                  });
                }}
              />
            </div>
          </div>
          {customInputConfig.showDescription && (
            <div className="mt-3 flex items-center">
              <FormLabel>{t('input_description')}</FormLabel>
              <TextArea
                className="text-gray-500"
                value={data.description}
                onChange={(e) => {
                  setData({
                    ...data,
                    description: e.target.value,
                  });
                }}
              />
            </div>
          )}
        </div>
        <div className="ml-auto mt-4 flex gap-3">
          <Button onClick={onClose}>{t('common.Close')}</Button>
          <Button
            type="primary"
            onClick={() => {
              onSubmitSuccess(data as any);
            }}
          >
            {t('common.Confirm')}
          </Button>
        </div>
      </div>
    </MyModal>
  );
};

export default FieldModal;

export const defaultInput: FlowNodeInputItemType = {
  renderTypeList: [FlowNodeInputTypeEnum.reference],
  valueType: WorkflowIOValueTypeEnum.string,
  canEdit: true,
  key: '',
  label: '',
};
